import router from '@/router/index'
import { deleteToken, getToken } from '@/composables/cookie/auth'
import { startLoading, doneLoading, showMessage } from '@/composables/utils'
import { useBlogSettingsStore } from '@/stores/blogsettings'
import { useUserStore } from '@/stores/user'



//全局前置守卫,防止用户能直接访问某些资源
router.beforeEach((to, from, next) => {
    //启用loading
    startLoading()

    // 未登录，则强制跳转登录页, 已登录就防止多次访问登录页
    let token = getToken()
    if (!token && to.path.startsWith('/admin')) {       //没有token但是访问了admin开头的路径
        useUserStore().logout()
        showMessage('please login???', 'warning')
        next({ path: '/' })
    } else if (token && to.path == '/login') {    //存在token 而且 登录login
        // 
        showMessage('You\'ve already logged in, so you don\'t need to log in again', 'info')
        next({ path: '/admin/index' })
    } else if (!to.path.startsWith('/admin')) {     //访问非 admin
        let blogSettingsStore = useBlogSettingsStore()     // 引入获取博客设置信息store
        blogSettingsStore.getBlogSettingsData()     // 获取博客设置信息,并保存到全局变量中
        next()
    } else {
        next()
    }
})

// 全局路由后置守卫
router.afterEach((to, from) => {
    //停用loading
    doneLoading()

    // 动态设置页面 title
    let title = (to.meta.title ? to.meta.title : '') + 'KittenBlog'
    document.title = title
    // 跳转后刷新页面
})